package com.sacc.service.Impl;

import com.power.common.model.CommonResult;
import com.sacc.clients.ProductClient;
import com.sacc.mapper.BoxProductMapper;
import com.sacc.pojo.BoxProduct;
import com.sacc.pojo.ProductInfoAll;
import com.sacc.pojo.ProductList;
import com.sacc.service.BoxProductService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author 滚~韬
 * @date 2022/4/12 13:30
 */
@Service
public class BoxProductServiceImpl implements BoxProductService {

    @Autowired
    private BoxProductMapper boxProductMapper;
    @Autowired
    private ProductClient productClient;

    /**
     * 根据boxid获取ProductInfoAll清单
     * @param boxId
     * @return
     */
    public List<ProductInfoAll> getByBoxId(Integer boxId){
        BoxProduct boxProduct = boxProductMapper.selectById(boxId);
        if(boxProduct==null){
            return Collections.EMPTY_LIST;
        }
        List<Integer> productIds =  Arrays.asList((Integer[]) ConvertUtils.convert(boxProduct.getProductId().split(","),Integer.class));
        List<ProductInfoAll> productInfoAlls = new ArrayList<>();
        productIds.forEach(p->{
            productInfoAlls.add(productClient.GetProductOneList(p));
        });
        return  productInfoAlls;
    }

    /***
     * 添加id
     * @param productId
     * @param boxId
     * @return
     */
    public CommonResult AddId(Integer productId,Integer boxId){
        BoxProduct boxProduct = boxProductMapper.selectById(boxId);
        if(boxProduct==null){
            BoxProduct product = new BoxProduct();
            product.setProductId(productId.toString());
            product.setBoxId(boxId);
            boxProductMapper.insert(product);
            return new CommonResult(true,"插入成功",product);
        }else{
            boxProduct.setProductId(boxProduct.getProductId()+","+productId);
            boxProductMapper.updateById(boxProduct);
            return new CommonResult(true,"更新成功",boxProduct);
        }
    }
}
